package org.ash.socket.aio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousServerSocketChannel;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;
import java.util.concurrent.TimeUnit;

/**
 * @Author: Ashin
 * @Date: 2021/1/26
 * @Description: org.ashin.socket.aio
 * @Version: 1.0.0
 */
public class AioServer {

    public static void main(String[] args) throws IOException, InterruptedException {
        AsynchronousServerSocketChannel aServerSocketChannel = AsynchronousServerSocketChannel.open().bind(new InetSocketAddress(8080));

        aServerSocketChannel.accept(null, new CompletionHandler<AsynchronousSocketChannel, Object>() {

            @Override
            public void completed(AsynchronousSocketChannel socketChannel, Object attachment) {
                try {
                    System.out.println("2----" + Thread.currentThread().getName());

                    // 如果不写这行代码后续的客户端连接不上服务端
                    aServerSocketChannel.accept(attachment, this);

                    System.out.println(socketChannel.getRemoteAddress());
                    ByteBuffer buffer = ByteBuffer.allocate(1024);
                    socketChannel.read(buffer, buffer, new CompletionHandler<Integer, ByteBuffer>() {
                        @Override
                        public void completed(Integer result, ByteBuffer attachment) {
                            System.out.println("3---" + Thread.currentThread().getName());

                            buffer.flip();
                            System.out.println(new String(buffer.array(), 0, result));

                            socketChannel.write(ByteBuffer.wrap("HelloClient".getBytes()));

                        }

                        @Override
                        public void failed(Throwable exc, ByteBuffer attachment) {
                            exc.printStackTrace();
                        }
                    });


                } catch (Exception e) {
                    e.printStackTrace();
                }


            }

            @Override
            public void failed(Throwable exc, Object attachment) {
                exc.printStackTrace();
            }
        });


        System.out.println("1-----" + Thread.currentThread().getName());

        TimeUnit.SECONDS.sleep(Integer.MAX_VALUE);
    }

}
